#include "IODeviceManager.h"
#include "ThinkGear/ThinkGearDevice.h"
#include "Tobii/TobiiDevice.h"
#include "ArduinoControllerDevice.h"

void InitialIODeviceManager(IODeviceContext* context)
{
	IODeviceManager::GetInstance()->Init(context);
}

IODeviceIF* GetDevice(IODeviceType type)
{
	return IODeviceManager::GetInstance()->GetDevice(type);
}

void DestroyIODeviceManager()
{
	IODeviceManager::Destroy();
}

IODeviceManager* IODeviceManager::m_pInstance = NULL;

IODeviceManager::IODeviceManager()
{

}

IODeviceManager::~IODeviceManager()
{
	std::map<IODeviceType, IODeviceIF*>::iterator it = m_mapDevices.begin();
	for (; it != m_mapDevices.end(); ++it) {
		delete it->second;
		it->second = NULL;
	}
}

void IODeviceManager::Init(IODeviceContext* context)
{
	for (int i = IO_DEVICE_INVALID + 1; i < IO_DEVICE_MAX; ++i) {
		IODeviceType type = static_cast<IODeviceType>(i);
		m_mapDevices.insert(std::pair<IODeviceType, IODeviceIF*>(type, NewDevice(type, context)));
	}
}

IODeviceManager* IODeviceManager::GetInstance()
{
	if (m_pInstance == NULL) {
		m_pInstance = new IODeviceManager;
	}
	return m_pInstance;
}

void IODeviceManager::Destroy()
{
	if (m_pInstance != NULL) {
		delete m_pInstance;
		m_pInstance = NULL;
	}
}

IODeviceIF* IODeviceManager::GetDevice(IODeviceType type)
{
	if (m_mapDevices.end() == m_mapDevices.find(type)) {
		return NULL;
	}
	return m_mapDevices[type];
}

IODeviceIF* IODeviceManager::NewDevice(IODeviceType type, IODeviceContext* context)
{
	switch (type)
	{
	case IO_DEVICE_INVALID:
		return NULL;
	case IO_DEVICE_TOBII:
		return new TobiiDevice(context);
	case IO_DEVICE_THINKGEAR:
		return new ThinkGearDevice(context);
	case IO_DEVICE_ARDUINO_CONTROLLER:
		return new ArduinoControllerDevice(context);
	default:
		return NULL;
	}
}